
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>在17道题中理解javascript的类型转换 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,原文地址
类型转换是将值从一种类型转换为另一种类型的过程（比如字符串转数字，对象转布尔值等）。任何类型不论是原始类型还是对象类型都可以进行类型转换，JavaScript 的原始类型有：number,,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">在17道题中理解javascript的类型转换</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                August 08, 2019
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2019/08/08/Js/%E5%9C%A817%E9%81%93%E9%A2%98%E4%B8%AD%E7%90%86%E8%A7%A3javascript%E7%9A%84%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/" title="在17道题中理解javascript的类型转换" class="">在17道题中理解javascript的类型转换</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    26k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    24 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Js/" rel="tag">Js</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <p><a href="https://juejin.im/post/5d4999fff265da038f47f5c7" target="_blank" rel="noopener">原文地址</a></p>
<p>类型转换是将值从一种类型转换为另一种类型的过程（比如字符串转数字，对象转布尔值等）。任何类型不论是原始类型还是对象类型都可以进行类型转换，JavaScript 的原始类型有：<code>number, string, boolean, null, undefined, Symbol</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">true</span> + <span class="literal">false</span></span><br><span class="line"><span class="number">12</span> / <span class="string">"6"</span></span><br><span class="line"><span class="string">"number"</span> + <span class="number">15</span> + <span class="number">3</span></span><br><span class="line"><span class="number">15</span> + <span class="number">3</span> + <span class="string">"number"</span></span><br><span class="line">[<span class="number">1</span>] &gt; <span class="literal">null</span></span><br><span class="line"><span class="string">"foo"</span> + + <span class="string">"bar"</span></span><br><span class="line"><span class="string">"true"</span> == <span class="literal">true</span></span><br><span class="line"><span class="literal">false</span> == <span class="string">"false"</span></span><br><span class="line"><span class="literal">null</span> == <span class="string">""</span></span><br><span class="line">!!<span class="string">"false"</span> == !!<span class="string">"true"</span></span><br><span class="line">[<span class="string">"x"</span>] == <span class="string">"x"</span></span><br><span class="line">[] + <span class="literal">null</span> + <span class="number">1</span></span><br><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>] == [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]</span><br><span class="line">&#123;&#125; + [] + &#123;&#125; + [<span class="number">1</span>]</span><br><span class="line">! + [] + [] + ![]</span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">0</span>) - <span class="number">0</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">0</span>) + <span class="number">0</span></span><br></pre></td></tr></table></figure>
<p>类似于上面的这些问题大概率也会在 JS 面试中被问到, 所以继续往下读。</p>
<h2 id="隐式转换VS显示转换"><a href="#隐式转换VS显示转换" class="headerlink" title="隐式转换VS显示转换"></a>隐式转换VS显示转换</h2><p>类型转换可以分为<strong>隐式类型转换</strong>和<strong>显式类型转换</strong>。</p>
<p>当开发人员通过编写适当的代码(如Number(value))用于在类型之间进行转换时，就称为<code>显式类型强制转换(或强制类型转换)</code>。</p>
<p>然而 JavaScript 是弱类型语言，在某些操作下，值可以在两种类型之间自动的转换，这叫做<code>隐式类型转换</code>。在对不同类型的值使用运算符时通常会发生隐式类型转换。比如 1 == null, 2 / “5”, null + new Date()。当值被 if 语句包裹时也有可能发生，比如 if(value) {} 会将 value 转换为 boolean类型。</p>
<p><code>严格相等运算符</code>（===）不会触发类型隐式转换，所以它可以用来比较值和类型是否都相等。</p>
<p><strong>隐式类型转换是一把双刃剑，使用它虽然可以写更少的代码但有时候会出现难以被发现的bug</strong>。</p>
<h2 id="三种类型转换"><a href="#三种类型转换" class="headerlink" title="三种类型转换"></a>三种类型转换</h2><p>我们需要知道的第一个规则是：<strong>在 JS 中只有 3 种类型的转换</strong></p>
<ul>
<li>to string</li>
<li>to boolean</li>
<li>to number</li>
</ul>
<p>第二，<strong>类型转换的逻辑在原始类型和对象类型上是不同的，但是他们都只会转换成上面 3 种类型之一</strong>。</p>
<p>我们首先分析一下原始类型转换。</p>
<h2 id="String-类型转换"><a href="#String-类型转换" class="headerlink" title="String 类型转换"></a>String 类型转换</h2><p><code>String()</code> 方法可以用来显式将值转为字符串，隐式转换通常在有 <code>+</code> 运算符并且有一个操作数是 <code>string</code> 类型时被触发，如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>(<span class="number">123</span>) <span class="comment">// 显式类型转换</span></span><br><span class="line"></span><br><span class="line"><span class="number">123</span> + <span class="string">''</span> <span class="comment">// 隐式类型转换</span></span><br></pre></td></tr></table></figure>
<p>所有原始类型转 String 类型</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>(<span class="number">123</span>)  <span class="comment">// '123'</span></span><br><span class="line"><span class="built_in">String</span>(<span class="number">-12.3</span>)  <span class="comment">// '-12.3'</span></span><br><span class="line"><span class="built_in">String</span>(<span class="literal">null</span>)  <span class="comment">// 'null'</span></span><br><span class="line"><span class="built_in">String</span>(<span class="literal">undefined</span>)  <span class="comment">// 'undefined'</span></span><br><span class="line"><span class="built_in">String</span>(<span class="literal">true</span>)  <span class="comment">// 'true'</span></span><br></pre></td></tr></table></figure>
<p>Symbol 类型转 String 类型是比较严格的，它只能被显式的转换</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>(<span class="built_in">Symbol</span>(<span class="string">'symbol'</span>))  <span class="comment">// 'Symbol(symbol)'</span></span><br><span class="line"></span><br><span class="line"><span class="string">''</span> + <span class="built_in">Symbol</span>(<span class="string">'symbol'</span>)  <span class="comment">// TypeError is thrown</span></span><br></pre></td></tr></table></figure>
<h2 id="Boolean-类型转换"><a href="#Boolean-类型转换" class="headerlink" title="Boolean 类型转换"></a>Boolean 类型转换</h2><p><code>Boolean()</code> 方法可以用来显式将值转换成 boolean 型。</p>
<p>隐式类型转换通常在逻辑判断或者有逻辑运算符时被触发<code>（|| &amp;&amp; !）</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Boolean</span>(<span class="number">2</span>)    <span class="comment">// 显示类型转换</span></span><br><span class="line"><span class="keyword">if</span>(<span class="number">2</span>) &#123;&#125;      <span class="comment">// 逻辑判断触发隐式类型转换</span></span><br><span class="line">!!<span class="number">2</span>           <span class="comment">// 逻辑运算符触发隐式类型转换</span></span><br><span class="line"><span class="number">2</span> || <span class="string">'hello'</span>  <span class="comment">// 逻辑运算符触发隐式类型转换</span></span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>注意: 逻辑运算符（比如 || 和 &amp;&amp;）是在内部做了 boolean 类型转换，但实际上返回的是<code>原始操作数的值</code>，即使他们都不是 boolean 类型。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 返回 number 类型 123，而不是 boolean 型 true</span></span><br><span class="line"><span class="comment">// 'hello' 和 '123' 仍然在内部会转换成 boolean 型来计算表达式</span></span><br><span class="line"><span class="keyword">let</span> x = <span class="string">'hello'</span> &amp;&amp; <span class="number">123</span>  <span class="comment">// x === 123</span></span><br></pre></td></tr></table></figure>
<p>boolean 类型转换只会有 true 或者 false 两种结果。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Boolean</span>(<span class="string">''</span>)           <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="number">0</span>)            <span class="comment">// false  </span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="number">-0</span>)           <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="literal">NaN</span>)          <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="literal">null</span>)         <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="literal">undefined</span>)     <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="literal">false</span>)        <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p><strong>任何不在上面列表中的值都会转换为 true</strong>, 包括 <code>object, function, Array, Date</code> 等，<code>Symbol</code> 类型是真值，空对象和空数组也是真值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Boolean</span>(&#123;&#125;)             <span class="comment">// true</span></span><br><span class="line"><span class="built_in">Boolean</span>([])             <span class="comment">// true</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="built_in">Symbol</span>())       <span class="comment">// true</span></span><br><span class="line">!!<span class="built_in">Symbol</span>()              <span class="comment">// true</span></span><br><span class="line"><span class="built_in">Boolean</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;)  <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<h2 id="Number-类型转换"><a href="#Number-类型转换" class="headerlink" title="Number 类型转换"></a>Number 类型转换</h2><p>和 <code>Boolean()</code>、<code>String()</code> 方法一样， <code>Number()</code> 方法可以用来显式将值转换成 number 类型。<br>number 的隐式类型转换是比较复杂的，因为它可以在下面多种情况下被触发。</p>
<ul>
<li>比较操作（&gt;, &lt;, &lt;=, &gt;=）</li>
<li>按位操作（| &amp; ^ ~）</li>
<li>算数操作（- + * / %）， 注意，当 + 操作存在任意的操作数是 string 类型时，不会触发 number 类型的隐式转换</li>
<li>一 元 + 操作</li>
<li>非严格相等操作（== 或者 != ），注意，== 操作两个操作数都是 string 类型时，不会发生 number 类型的隐式转换</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Number</span>(<span class="string">'123'</span>)    <span class="comment">// 显示类型转换</span></span><br><span class="line">+ <span class="string">'123'</span>          <span class="comment">//  隐式类型转换</span></span><br><span class="line"><span class="number">123</span> != <span class="string">"456"</span>    <span class="comment">//  隐式类型转换</span></span><br><span class="line"><span class="number">4</span> &gt; <span class="string">"5"</span>        <span class="comment">//  隐式类型转换</span></span><br><span class="line"><span class="number">5</span> / <span class="literal">null</span>      <span class="comment">//  隐式类型转换</span></span><br><span class="line"><span class="literal">true</span> | <span class="number">0</span>      <span class="comment">//  隐式类型转换</span></span><br></pre></td></tr></table></figure>
<p>接下来看一下原始类型显示转换 number 类型会发生什么</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Number</span>(<span class="literal">null</span>)                   <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="literal">undefined</span>)              <span class="comment">// NaN</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="literal">true</span>)                   <span class="comment">// 1</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="literal">false</span>)                  <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="string">" 12 "</span>)                 <span class="comment">// 12</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="string">"-12.34"</span>)               <span class="comment">// -12.34</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="string">"\n"</span>)                   <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="string">" 12s "</span>)                <span class="comment">// NaN</span></span><br><span class="line"><span class="built_in">Number</span>(<span class="number">123</span>)                    <span class="comment">// 123</span></span><br></pre></td></tr></table></figure>
<p>当将一个字符串转换为一个数字时，引擎首先删除前尾空格、<code>\n、\t</code> 字符，如果被修剪的字符串不成为一个有效的数字，则返回 NaN。如果字符串为空，则返回 0。</p>
<p>Number() 方法对于 null 和 undefined 的处理是不同的， null 会转换为 0, undefined 会转换为 NaN</p>
<p><strong>不管是显式还是隐式转换都不能将 Symbol 类型转为 number 类型，当试图这样操作时，会抛出错误</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Number</span>(<span class="built_in">Symbol</span>(<span class="string">'my symbol'</span>))    <span class="comment">// TypeError is thrown</span></span><br><span class="line">+<span class="built_in">Symbol</span>(<span class="string">'123'</span>)                 <span class="comment">// TypeError is thrown</span></span><br></pre></td></tr></table></figure>
<p>这里<strong>有 2 个特殊的规则</strong>需要记住：</p>
<ol>
<li>当将 == 应用于 null 或 undefined 时，不会发生数值转换。null 只等于 null 或 undefined，不等于其他任何值。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">null</span> == <span class="number">0</span>               <span class="comment">// false, null is not converted to 0</span></span><br><span class="line"><span class="literal">null</span> == <span class="literal">null</span>            <span class="comment">// true</span></span><br><span class="line"><span class="literal">undefined</span> == <span class="literal">undefined</span>  <span class="comment">// true</span></span><br><span class="line"><span class="literal">null</span> == <span class="literal">undefined</span>       <span class="comment">// true</span></span><br><span class="line"><span class="literal">undefined</span> == <span class="number">0</span>          <span class="comment">// false</span></span><br></pre></td></tr></table></figure></li>
<li>NaN 不等于任何值，包括它自己</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">NaN</span> === <span class="literal">NaN</span>  <span class="comment">// false</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span>(value !== value) &#123; <span class="built_in">console</span>.log(<span class="string">'the value is NaN'</span>) &#125;</span><br></pre></td></tr></table></figure>
<h2 id="object-类型转换"><a href="#object-类型转换" class="headerlink" title="object 类型转换"></a>object 类型转换</h2><p>到这里我们已经深入了解了原始类型的转换，接下来我们来看一下 object 类型的转换。</p>
<p>当涉及到对象的操作比如：<code>[1] + [2,3]</code>，引擎首先会尝试将 object 类型转为原始类型，然后在将原始类型转为最终需要的类型，而且仍然只有 3 种类型的转换：<code>number, string, boolean</code></p>
<p>最简单的情况是 boolean 类型的转换，任何非原始类型总是会转换成 true,无论对象或数组是否为空。</p>
<p>对象通过内部 <code>[[ToPrimitive]]</code> 方法转换为原始类型，该方法负责数字和字符串转换。</p>
<p><code>[[ToPrimitive]]</code> 方法接受两个参数一个输入值和一个需要转换的类型<code>（Numer or String）</code><br>number 和 string的转换都使用了对象的两个方法： <code>valueOf</code> 和 <code>toString</code>。这两个方法都在 <code>Object.prototype</code> 上被声明，因此可用于任何派生类，比如 <code>Date, Array</code>等。</p>
<blockquote>
<p>通常上 [[ToPrimitive]] 算法如下：</p>
</blockquote>
<ul>
<li>如果输入的值已经是原始类型，直接返回这个值。</li>
<li>输入的值调用 toString() 方法，如果结果是原始类型，则返回。</li>
<li>输入的值调用 valueOf() 方法，如果结果是原始类型，则返回。</li>
<li>如果上面 3 个步骤之后，转换后的值仍然不是原始类型，则抛出 TypeError 错误。</li>
</ul>
<p>number 类型的转换首先会调用 <code>valueOf()</code> 方法，如果不是原始值在调用 <code>toString()</code> 方法。 string 类型的转换则相反。</p>
<p>大多数 JS 内置对象类型的 valueOf() 返回这个对象本身，其结果经常被忽略，因为它不是一个原始类型。所以大多数情况下当 object 需要转换成 number 或 string 类型时最终都调用了 <code>toString()</code> 方法。</p>
<p>当运算符不同时，<code>[[ToPrimitive]]</code> 方法接受的转换类型参数也不相同。当存在 == 或者 + 运算符时一般会先触发 number 类型的转换再触发 string 类型转换。</p>
<p>在 JS 中你可以通过重写对象的 <code>toString 和 valueOf</code> 方法来修改对象到原始类型转换的逻辑。</p>
<h2 id="答案解析"><a href="#答案解析" class="headerlink" title="答案解析"></a>答案解析</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">true</span> + <span class="literal">false</span> <span class="comment">// 1  </span></span><br><span class="line"><span class="comment">// '+' 运算符会触发 number 类型转换对于 true 和 false</span></span><br><span class="line"></span><br><span class="line"><span class="number">12</span> / <span class="string">"6"</span> <span class="comment">// 2       </span></span><br><span class="line"><span class="comment">//算数运算符会把字符串 ‘6’ 转为 number 类型</span></span><br><span class="line"></span><br><span class="line"><span class="string">"number"</span> + <span class="number">15</span> + <span class="number">3</span> <span class="comment">// 'number153'</span></span><br><span class="line"><span class="comment">// '+' 运算符按从左到右的顺序的执行，所以优先执行 “number” + 15, 把 15 转为 string 类型，得到 “number15” 然后同理执行 “number15” + 3</span></span><br><span class="line"></span><br><span class="line"><span class="number">15</span> + <span class="number">3</span> + <span class="string">"number"</span>  <span class="comment">// "18number"</span></span><br><span class="line"><span class="comment">// 15 + 3 先执行，运算符两边都是 number 类型 ，不用转换，然后执行 18 + “number” 最终得到 “18number”</span></span><br><span class="line"></span><br><span class="line">[<span class="number">1</span>] &gt; <span class="literal">null</span> <span class="comment">// true</span></span><br><span class="line"><span class="comment">// ==&gt; '1' &gt; 0</span></span><br><span class="line"><span class="comment">// ==&gt; 1 &gt; 0</span></span><br><span class="line"><span class="comment">// ==&gt; true</span></span><br><span class="line"><span class="comment">// 比较运算符 &gt; 执行 number 类型隐式转换。</span></span><br><span class="line"></span><br><span class="line"><span class="string">"foo"</span> + + <span class="string">"bar"</span> <span class="comment">// "fooNaN"</span></span><br><span class="line"><span class="comment">// ==&gt; "foo" + (+"bar")</span></span><br><span class="line"><span class="comment">// ==&gt; "foo" + NaN</span></span><br><span class="line"><span class="comment">// ==&gt; "fooNaN"</span></span><br><span class="line"><span class="comment">// 一元 + 运算符比二元 + 运算符具有更高的优先级。所以 + bar表达式先求值。一元加号执行字符串“bar” 的 number 类型转换。因为字符串不代表一个有效的数字，所以结果是NaN。在第二步中，计算表达式'foo' + NaN。</span></span><br><span class="line"></span><br><span class="line"><span class="string">"true"</span> == <span class="literal">true</span> <span class="comment">// false</span></span><br><span class="line"><span class="literal">false</span> == <span class="string">"false"</span> <span class="comment">// false</span></span><br><span class="line"><span class="comment">// == 运算符执行 number 类型转换，'true' 转换为 NaN， boolean 类型 true 转换为 1</span></span><br><span class="line"></span><br><span class="line"><span class="literal">null</span> == <span class="string">""</span> <span class="comment">// false</span></span><br><span class="line"><span class="comment">// null 不等于任何值除了 null 和 undefined</span></span><br><span class="line"></span><br><span class="line">!!<span class="string">"false"</span> == !!<span class="string">"true"</span> <span class="comment">// true</span></span><br><span class="line"><span class="comment">// !! 运算符将字符串 'true' 和 'false' 转为 boolean 类型 true, 因为不是空字符串，然后两边都是 boolean 型不在执行隐式转换操作。</span></span><br><span class="line"></span><br><span class="line">[<span class="string">"x"</span>] == <span class="string">"x"</span> <span class="comment">// true</span></span><br><span class="line"><span class="comment">// == 运算符对数组类型执行 number 转换，先调用对象的 valueOf() 方法，结果是数组本身，不是原始类型值，所以执行对象的 toString() 方法，得到字符串 'x'</span></span><br><span class="line"></span><br><span class="line">[] + <span class="literal">null</span> + <span class="number">1</span> <span class="comment">// 'null1'</span></span><br><span class="line"><span class="comment">// '+' 运算符执行 number 类型转换，先调用对象的 valueOf() 方法，结果是数组本身，不是原始类型值，所以执行对象的 toString() 方法，得到字符串 ''， 接下来执行表达式 '' + null + 1。</span></span><br><span class="line"></span><br><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>] == [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>] <span class="comment">// false</span></span><br><span class="line"><span class="comment">// 当运算符两边类型相同时，不会执行类型转换，两个数组的内存地址不一样，所以返回 false</span></span><br><span class="line"></span><br><span class="line"><span class="number">0</span> || <span class="string">"0"</span> &amp;&amp; &#123;&#125;  <span class="comment">// &#123;&#125;</span></span><br><span class="line"><span class="comment">// 逻辑运算符 || 和 &amp;&amp; 将值转为 boolean 型，但是会返回原始值（不是 boolean）。</span></span><br><span class="line"></span><br><span class="line">&#123;&#125; + [] + &#123;&#125; + [<span class="number">1</span>] <span class="comment">// '0[object Object]1'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 所有的操作数都不是原始类型，所以会按照从左到右的顺序执行 number 类型的隐式转换， object 和 array 类型的 valueOf() 方法返回它们本身，所以直接忽略，执行 toString() 方法。 这里的技巧是，第一个 &#123;&#125; 不被视为 object，而是块声明语句，因此它被忽略。计算从 +[] 表达式开始，该表达式通过toString()方法转换为空字符串，然后转换为0。</span></span><br><span class="line"></span><br><span class="line">! + [] + [] + ![] <span class="comment">// 'truefalse'</span></span><br><span class="line"><span class="comment">// 一元运算符优先执行，+[] 转为 number 类型 0，![] 转为 boolean 型 false。</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">0</span>) - <span class="number">0</span> <span class="comment">// 0</span></span><br><span class="line"><span class="comment">// '-' 运算符执行 number 类型隐式转换对于 Date 型的值，Date.valueOf() 返回到毫秒的时间戳。</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">0</span>) + <span class="number">0</span> <span class="comment">//"Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)0"</span></span><br><span class="line"><span class="comment">// +' 运算符触发默认转换，因此使用 toString() 方法，而不是 valueOf()。</span></span><br></pre></td></tr></table></figure>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#隐式转换VS显示转换"><span class="toc-number">1.</span> <span class="toc-text">隐式转换VS显示转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三种类型转换"><span class="toc-number">2.</span> <span class="toc-text">三种类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#String-类型转换"><span class="toc-number">3.</span> <span class="toc-text">String 类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Boolean-类型转换"><span class="toc-number">4.</span> <span class="toc-text">Boolean 类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Number-类型转换"><span class="toc-number">5.</span> <span class="toc-text">Number 类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#object-类型转换"><span class="toc-number">6.</span> <span class="toc-text">object 类型转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#答案解析"><span class="toc-number">7.</span> <span class="toc-text">答案解析</span></a></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
